﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Documents;
using Sora.Data.Common.Streams;
using System.Windows.Markup;

namespace Sora.HelpSystem.Package.DataObjects
{
    public class FloatingFlowDocumentProperty : ICachedFlowDocumentProperty
    {
        private FlowDocument BaseDocument { get; set; }

        private FlowDocument CopiedDocument { get; set; }

        private FlowDocument Copy(FlowDocument document)
        {
            using (var stream = TemporaryStream.Create())
            {
                XamlWriter.Save(document, stream);
                stream.Position = 0;

                return (FlowDocument)XamlReader.Load(stream);
            }
        }

        public FloatingFlowDocumentProperty(FlowDocument doc)
        {
            if (doc == null)
                throw new ArgumentNullException("doc");

            BaseDocument = doc;
            DiscardChanges();
        }

        #region ICachedFlowDocumentProperty Members

        public void DiscardChanges()
        {
            CopiedDocument = Copy(BaseDocument);
        }

        public FlowDocument GetCopy()
        {
            return Copy(BaseDocument);
        }

        public void Commit()
        {
            throw new InvalidOperationException();
        }

        public FlowDocument Source
        {
            get
            {
                return CopiedDocument;
            }
            set
            {
                BaseDocument = value;
                DiscardChanges();
            }
        }

        #endregion
    }
}
